<script setup>
import { reactive, ref } from 'vue';
import { loginResquest, mustRolesLogin, getUserInfo } from '../../api/index.js';

const emit = defineEmits(['changeType', 'username']);

// 用户登录信息
let user = reactive({
  username: '',
  password: '',
});

// 多角色登录
let dialogVisible = ref(false);
let roleList = ref([]);
let selectLoginRadio = ref({});

// 点击登录
const login = async () => {
  if (!user.username || !user.password) {
    ElMessage.warning('用户名，密码不能为空');
    return;
  }
  const res = await loginResquest(user);
  if (res.success) {
    if (res?.data) {
      roleList.value = res.data[0].list;
      dialogVisible.value = true;
    } else {
      successLoginHandler()
    }
  }
};

const roleSelect = async () => {
  const data = { ...roleList.value[selectLoginRadio.value] };
  const res = await mustRolesLogin(data);
  if (res.success) {
    successLoginHandler()
  }
};

const successLoginHandler = async () => {
  cookies();
  const res = await getUserInfo();
  if(res.success) {
    emit('username', res.data.realName)
    chrome.storage.local.set({username: res.data.realName});
    emit('changeType', 'data');
  }
};

const cookies = () => {
  chrome.cookies.getAll(
    { domain: '.aicaichina.com', name: 'uid' },
    (cookies) => {
      chrome.storage.local.set({ cookies: cookies[0].value });
    },
  );
};
</script>

<template>
  <el-form :model="user" label-width="70px">
    <el-form-item label="用户名" prop="username">
      <el-input type="text" v-model="user.username" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="user.password" autocomplete="off" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="login">登录</el-button>
    </el-form-item>
  </el-form>

  <div class="operate-dec">
    <div>第一次使用时打开页面后请刷新再点击插件！</div>
    <br />
    <div>当前仅支持猎聘、boss、领英、51job、智联！</div>
  </div>

  <el-dialog v-model="dialogVisible" width="100%">
    <el-radio
      v-for="(item, index) in roleList"
      :key="item.jid"
      v-model="selectLoginRadio"
      :label="index"
      >{{ item.orgNames }}</el-radio
    >
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="roleSelect">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.operate-dec {
  margin-top: 60px;
  font-size: 18px;
  color: #999;
}
</style>
